/**
 * 
 */
package edu.pw.treegrid.server.classmodel;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import edu.pw.treegrid.server.query.ColumnNode;
import edu.pw.treegrid.server.query.Node;
import edu.pw.treegrid.server.query.TableNode;
import edu.pw.treegrid.server.reportmodel.ReportColumn;
import edu.pw.treegrid.server.service.XMLMarshaller;

/** 
 * @author Piotrek
 */
public class DictionaryAttribute extends ReferenceAttribute {
	public static final String REFERENCE_ATTRIBUTE_ELEMENT = "referenceAttribute";
	private DomainAttribute referenceAttribute;
	private String referenceAttributeId;
	
	public DomainAttribute getReferenceAttribute() {
		return referenceAttribute;
	}

	public void setReferenceAttribute(DomainAttribute referenceAttribute) {
		this.referenceAttribute = referenceAttribute;
	}

	public Node buildQueryNode(ReportColumn reportColumn) {
		TableNode tn = (TableNode) super.buildQueryNode(reportColumn);
		tn.addChild(getReferenceAttribute().buildQueryNode(reportColumn));
		tn.setReportColumn(reportColumn);
		//TODO
		//Do rozwazenia czy to poprawne:
		if (getReferenceAttribute() instanceof SimpleAttribute) {
			ColumnNode cn = (ColumnNode)getReferenceClass().getPrimaryAttribute()
			.buildQueryNode(reportColumn);
			cn.setIdColumn(true);
			cn.setReportColumn(reportColumn);
			tn.addChild(cn);
		}
		return tn;
	}

	public SimpleAttribute getSimpleAttribute() {
		return getReferenceAttribute().getSimpleAttribute();
	}
	
	@Override
	protected void serializeToXML(Document document, Element attributeElement) {
		super.serializeToXML(document, attributeElement);
		
		Element referenceAttributeElement = document.createElement(REFERENCE_ATTRIBUTE_ELEMENT);
		referenceAttributeElement.setAttribute(REF_ATTRIBUTE, referenceAttribute.getId());
		attributeElement.appendChild(referenceAttributeElement);
	}
	
	@Override
	protected void deserializeFromXML(Element ae) {
		super.deserializeFromXML(ae);
		
		this.referenceAttributeId = getAttributeText(getFirstElement(ae, REFERENCE_ATTRIBUTE_ELEMENT), REF_ATTRIBUTE);
	}
	
	@Override
	public void setReferences(XMLMarshaller xmlMarshaller) {
		super.setReferences(xmlMarshaller);
		
		this.referenceAttribute = xmlMarshaller.getAttributeById(referenceAttributeId);
	}

}